package com.neu.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.neu.po.Food;
import com.neu.po.Merchant;
import com.neu.po.Shopadmin;
import com.neu.po.User;
import com.neu.util.DBUtil;

public class ShopadminDaolmpl implements ShopadminDao{

	@Override
	public Shopadmin login(int mid, String password) throws ClassNotFoundException, SQLException {
		String sql = "select * from shopadmin where mid = ? and password =?";
		Connection connection = DBUtil.getConnection();
		ResultSet rs = DBUtil.executeQuery(connection, sql,mid,password);
		
		Shopadmin shopadmin = null;
		if(rs.next()) {
			mid = rs.getInt("mid");
			password = rs.getString("password");
			
			shopadmin = new Shopadmin(mid,password);
		}
		
		DBUtil.closeConnection(connection);
		return shopadmin;
	}


	@Override
	public int updatePassword(String oldPassword, String newPassword, int mid)
			throws ClassNotFoundException, SQLException {
		String sql = "select * from shopadmin where mid = ? and password = ?";
		Connection connection = DBUtil.getConnection();
		ResultSet rs = DBUtil.executeQuery(connection, sql, mid,oldPassword);
		int n = 0;
		if(rs. next()) {
			sql = "update shopadmin set password = ? where mid = ?";
			n = DBUtil.executeUpdate(sql, newPassword,mid);
			
		}
		DBUtil.closeConnection(connection);
		return n;
	}


	@Override
	public Merchant getById(int mid) throws ClassNotFoundException, SQLException {
		String sql = "select*from merchant join shopadmin on merchant.mid = shopadmin.mid where shopadmin.mid = ?";
		Connection connection = DBUtil.getConnection();
		ResultSet rs = DBUtil.executeQuery(connection, sql, mid);
		Merchant merchant = null;
    	String mname;
    	String loc;
    	String meg;
    	Double sfee;
    	Double ffee;
		
		if(rs.next()) {
			mid = rs.getInt("shopadmin.mid");
			mname = rs.getString("mname");
			loc = rs.getString("loc");
			meg = rs.getString("meg");
			sfee = rs.getDouble("sfee");
			ffee = rs.getDouble("ffee");
			
			merchant = new Merchant(mid, mname, loc, meg, sfee, ffee);
		}
		
		DBUtil.closeConnection(connection);
		return merchant;
	}


	@Override
	public int updateshop(Merchant merchant) throws ClassNotFoundException, SQLException {
		String sql = "update merchant join shopadmin on merchant.mid = shopadmin.mid set mname=?,loc=?,meg=?,sfee=?,ffee=? where shopadmin.mid =?";
		int n = DBUtil.executeUpdate(sql, merchant.getMname(),merchant.getLoc(),merchant.getMeg(),merchant.getSfee(),merchant.getFfee(),merchant.getMid());
		
		
		return n;
	}

}
